package test.core.safe;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import java.util.Arrays;
import java.util.Base64;

import org.junit.Test;

import hyl.core.AIni;
import hyl.core.MyFun;
import hyl.core.fun.MyByte;
import hyl.core.io.MyFile;
import hyl.core.run.IDo2;
import hyl.core.safe.MyBase64;
import hyl.core.safe.RsaCert;

public class testputtyrsa {
	public static  void main(String[] args) {

	}

	
	//@Test
	public  void test1_1() throws Exception {
		String 存储路径="D:\\work\\java\\hyl.test\\src\\key\\public1.txt";
		 //get(存储路径);
		String ssString=MyFile.read(new FileInputStream(存储路径));
		ssString=ssString.replace("\r\n", "").replace("\n", "");
		System.out.println(ssString);
		string2PublicKey(ssString);
		//string2PrivateKey(ssString);
	}
//ok
	public  void test1_2() throws Exception {
		String 存储路径="D:\\work\\java\\hyl.test\\src\\key\\public1.txt";
		 //get(存储路径);
		String ssString=MyFile.read(new FileInputStream(存储路径));
		ssString=ssString.replace("\r\n", "").replace("\n", "");
		System.out.println(ssString);
		decodePublicKey(ssString);
		//string2PrivateKey(ssString);
	}
	//@Test
	public  void test1_3() throws Exception {
		String 存储路径="D:\\work\\java\\hyl.test\\src\\key\\public2.txt";
		getpub(存储路径);
		//string2PrivateKey(ssString);
	}
	//@Test
	public  void test2_1() throws Exception {
		String 存储路径="D:\\work\\java\\hyl.test\\src\\key\\private1.txt";
		 //get(存储路径);
	
		String ssString=MyFile.read(new FileInputStream(存储路径));
		ssString=ssString.replace("\r\n", "").replace("\n", "");
		//getpri(存储路径);		
		string2PrivateKey(ssString);
		//string2PrivateKey(ssString);
	}
	//@Test
	public  void test2_2() throws Exception {
		String 存储路径="D:\\work\\java\\hyl.test\\src\\key\\private1.txt";
		 //get(存储路径);
		String ssString=MyFile.read(new FileInputStream(存储路径));
		ssString=ssString.replace("\r\n", "").replace("\n", "");
		System.out.println(ssString);
		decodePrivateKey(ssString);
		//string2PrivateKey(ssString);
	}
	@Test
	public void test2_3() throws IOException, ClassNotFoundException {
		String 存储路径="D:\\work\\java\\hyl.test\\src\\key\\2.ppk";
	      // 获取私钥
        FileInputStream f = new FileInputStream(存储路径);
        ObjectInputStream b = new ObjectInputStream(f);
        RSAPrivateKey prk = (RSAPrivateKey) b.readObject();
	}
	public static PublicKey getpub(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
	public static PrivateKey getpri(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
      //  X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }
	public static PublicKey string2PublicKey(String pubStr) throws Exception{
		ByteBuffer byteBuffer =
		ByteBuffer.wrap(Base64.getMimeDecoder().decode(pubStr));
		byte[] keyBytes = byteBuffer.array();
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		
		return publicKey;
		}
	public static PrivateKey string2PrivateKey(String str) throws Exception{
		ByteBuffer byteBuffer =
		ByteBuffer.wrap(Base64.getMimeDecoder().decode(str));
		byte[] keyBytes = byteBuffer.array();
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey key = keyFactory.generatePrivate(keySpec);
		return key;
		}
	
	 public static int decodeUInt32(byte[] key, int start_index){  
	        byte[] test = Arrays.copyOfRange(key, start_index, start_index + 4);  
	        return new BigInteger(test).intValue();  
//	      int int_24 = (key[start_index++] << 24) & 0xff;   
//	      int int_16 = (key[start_index++] << 16) & 0xff;   
//	      int int_8 = (key[start_index++] << 8) & 0xff;   
//	      int int_0 = key[start_index++] & 0xff;   
//	      return int_24 + int_16 + int_8 + int_0;   
	    }  
	 public static RSAPublicKey decodePublicKey(String keyStr) throws NoSuchAlgorithmException, InvalidKeySpecException{  
			ByteBuffer byteBuffer =
					ByteBuffer.wrap(Base64.getMimeDecoder().decode(keyStr));
					byte[] key = byteBuffer.array();
		 
		 byte[] sshrsa = new byte[] { 0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's',  
		    'a' };  
		    int start_index = sshrsa.length;  
		    /* Decode the public exponent */  
		    int len = decodeUInt32(key, start_index);  
		    start_index += 4;  
		    byte[] pe_b = new byte[len];  
		    for(int i= 0 ; i < len; i++){  
		        pe_b[i] = key[start_index++];  
		    }  
		    BigInteger pe = new BigInteger(pe_b);  
		    /* Decode the modulus */  
		    len = decodeUInt32(key, start_index);  
		    start_index += 4;  
		    byte[] md_b = new byte[len];  
		    for(int i = 0 ; i < len; i++){  
		        md_b[i] = key[start_index++];  
		    }  
		    BigInteger md = new BigInteger(md_b);  
		    KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
		    KeySpec ks = new RSAPublicKeySpec(md, pe);  
		    return (RSAPublicKey) keyFactory.generatePublic(ks);  
		}  
	 public static RSAPrivateKey decodePrivateKey(String keyStr) throws NoSuchAlgorithmException, InvalidKeySpecException{  
			ByteBuffer byteBuffer =
					ByteBuffer.wrap(Base64.getMimeDecoder().decode(keyStr));
					byte[] key = byteBuffer.array();
		 
		 byte[] sshrsa = new byte[] { 0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's',  'a' };  
		 System.out.println("----------------");
		 for(int i= 11 ; i < 15; i++){  
		      
			   System.out.print( key[i]);
			   System.out.print(' ');
		    }  
		 System.out.println("----------------");
		    int start_index = sshrsa.length;  
		    /* Decode the public exponent */  
		    int len = MyByte.bytes2int(key, start_index);  
			 System.out.println(len);
		    start_index += 4;  
		    byte[] pe_b = new byte[len];  
		    for(int i= 0 ; i < len; i++){  
		        pe_b[i] = key[start_index++];  
		     
		    }  
		    BigInteger pe = new BigInteger(pe_b);  
		    /* Decode the modulus */  
		    len = decodeUInt32(key, start_index);  
		    start_index += 4;  
		    byte[] md_b = new byte[len];  
		    for(int i = 0 ; i < len; i++){  
		        md_b[i] = key[start_index++];  
		    }  
		    BigInteger md = new BigInteger(md_b);  
		    KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
		    KeySpec ks = new RSAPublicKeySpec(md, pe);  
		    return (RSAPrivateKey) keyFactory.generatePrivate(ks);  
		}  
	 
	 /**
		 * 对于putty 的 rsa 格式文本 目前还无法解析
		 * @param file
		 * @return
		 */
		public void loadPuttyKey(File file) {

			if (file.exists()) {
				class RsaKey {
					String pubKey;
					String priKey;
				}
				IDo2<String> h解析key = new IDo2<String>() {
					int len = 0, st = 0;
					StringBuilder sbBuilder = null;
					RsaKey key = new RsaKey();

					@Override
					public void run(String line) {
						if (len == 0) {
							if (st == 0) {
								if (line.startsWith("Public-Lines:")) {
									len = MyFun.str2int(line.substring(13).trim());
									sbBuilder = new StringBuilder();
									st = 1;
								} else if (line.startsWith("Private-Lines:")) {
									len = MyFun.str2int(line.substring(14).trim());
									sbBuilder = new StringBuilder();
									st = 2;
								}
							}
						} else if (len > 0) {
							sbBuilder.append(line);
							len--;
							if (len == 0) {
								if (st == 1) {
									key.pubKey = sbBuilder.toString();
									MyFun.print("key.pubKey", key.pubKey);
								} else if (st == 2) {
									key.priKey = sbBuilder.toString();
									MyFun.print("key.priKey", key.priKey);
								}
								st = 0;
							}
						}
					}

					@Override
					public Object getResult() {
						return key;
					}
				};
				try {
					MyFile.readLine(new FileInputStream(file), AIni.charset, h解析key);
					RsaKey key = (RsaKey) h解析key.getResult();
					if (key == null)
						return ;
					// load公钥文本(key.pubKey);
					// byte[] bytes = MyBase64.decode(key.pubKey);
					// _pubkey = bytes2RsaPubKey(bytes);
					//System.out.println(key.priKey);

//					_prikey = bytes2RsaPriKey(key.priKey);
					// load私钥文本(key.priKey);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return ;
		}
	/**
	 * 对于 openssh 和putty 的文件格式目前无法解析
	 * @param file
	 * @return
	 */
		public void loadPuttyPubKey(File file) {

			if (file.exists()) {
				IDo2<String> h解析pubkey = new IDo2<String>() {
					int st = 0;
					StringBuilder sbBuilder = new StringBuilder();
					String key;

					@Override
					public void run(String line) {
						if (st == 0) {
							if (line.startsWith("Comment:")) {
								st = 1;
							}
						} else if (st == 1) {
							st = 2;
						} else if (st == 2) {
							if (line.startsWith("----")) {
								key = sbBuilder.toString();
							} else {
								sbBuilder.append(line);
							}
						}
					}

					@Override
					public Object getResult() {
						return key;
					}
				};
				try {
					MyFile.readLine(new FileInputStream(file), AIni.charset, h解析pubkey);
					String str = (String) h解析pubkey.getResult();
					// load公钥文本(str);
					byte[] key = MyBase64.decode(str);
//					_pubkey = this.bytes2PubkeyPKCS8(key);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return ;
		}
}
